﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using DataAccess.DB;
using DuocThaiBinh.Common;
using DuocThaiBinh.HtmlHelpers;
using DuocThaiBinh.HtmlHelpers.ExportToExcel;
using Newtonsoft.Json;
using WebMatrix.WebData;

namespace DuocThaiBinh.Controllers
{
    public class SanPhamController : BaseController
    {
        private db_YTeTBEntities db = new db_YTeTBEntities();

        //
        // GET: /SanPham/
        [Authorize(Roles = "Administrator,Staff,StaffXuatKho")]
        public ActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = "Administrator,Staff,StaffXuatKho")]
        public JsonResult IndexGet()
        {
            var sps = db.SanPhams.OrderBy(p => p.MaSP).Where(p => p.MaSP != null && p.Disable == null).ToList();

            return Json(new
            {
                data = sps.Select(x => new { MaSP = x.MaSP, TenSP = x.TenSP, ID = x.ID })
            }, JsonRequestBehavior.AllowGet);
        }

        [Authorize(Roles = "Administrator,Staff,StaffXuatKho")]
        [HttpPost]
        public JsonResult Index(int page, int rows, string sidx, string sord, string filters, bool _search)
        {
            var SanPham = db.SanPhams.OrderBy(p => p.MaSP).Where(p => p.MaSP != null && p.Disable == null).ToList() as IEnumerable<SanPham>;

            if (_search)
            {
                FiltersJq f = (!_search || string.IsNullOrEmpty(filters)) ? null : JsonConvert.DeserializeObject<FiltersJq>(filters);
                for (int i = 0; i < f.rules.Count; i++)
                {
                    string field = f.rules[i].field;
                    string data = f.rules[i].data;
                    switch (field)
                    {
                        case "MaSP": SanPham = SanPham.Where(p => p.MaSP.ToLower().Contains(data.ToLower())); break;
                        case "TenSP": SanPham = SanPham.Where(p => p.TenSP.ToLower().Contains(data.ToLower())); break;
                        default: SanPham.Where(p => p.MaSP.ToLower().Contains(data.ToLower())); break;
                    }
                }

            }

            var count = SanPham.Count<SanPham>();
            int total;
            if (count == 0)
                total = 0;
            else
                total = (int)Math.Ceiling((decimal)count / rows);

            var pagedResult = SanPham.Skip(rows * (page - 1)).Take(rows).ToList();

            var result = new
            {
                total = total,
                page = page,
                records = count,
                rows = pagedResult.Select(x => new { x.ID, x.MaSP, x.TenSP, x.HSD, x.GiaBan, x.DonVi })

            };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult GetProductById(string selectedValue)
        {
            SanPham sp = db.SanPhams.Find(Convert.ToInt32(selectedValue));

            string list = Convert.ToString(sp.MaSP + ";#" + sp.GiaNhap + ";#" + sp.DonVi + ";#" + sp.TenSP);
            return Json(new { ProductDetail = list });
        }
        //Lay san pham khi xuat kho 
        [HttpPost]
        public JsonResult GetProductXKById(string selectedValue)
        {
            SanPham sp = db.SanPhams.Find(Convert.ToInt32(selectedValue));

            string list = Convert.ToString(sp.MaSP + ";#" + sp.GiaBan + ";#" + sp.DonVi + ";#" + sp.TenSP);
            return Json(new { ProductDetail = list });
        }

        //Lay san pham khi xuat kho 
        public string[] GetProductByMa(string selectedValue)
        {
            SanPham sp = db.SanPhams.Where(p => p.MaSP == selectedValue).FirstOrDefault();
            if (sp == null) return null;
            return new string[] { sp.ID.ToString(), sp.MaSP, sp.DonVi };
        }

        //
        // GET: /SanPham/Details/5
        [Authorize(Roles = "Administrator")]
        public ActionResult Details(int id = 0)
        {
            SanPham sanpham = db.SanPhams.Find(id);
            if (sanpham == null)
            {
                return HttpNotFound();
            }
            
            return View(sanpham);
        }

        //
        // GET: /SanPham/Create
        [Authorize(Roles = "Administrator")]
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /SanPham/Create
        [Authorize(Roles = "Administrator")]
        [HttpPost]
        public ActionResult Create(SanPham sanpham)
        {
            if (ModelState.IsValid)
            {
                if (sanpham.GiaBan == null)
                {
                    sanpham.GiaBan = "0";
                }
                if (sanpham.GiaNhap == null)
                {
                    sanpham.GiaNhap = "0";
                }
                db.SanPhams.Add(sanpham);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(sanpham);
        }

        //
        // GET: /SanPham/Edit/5
        [Authorize(Roles = "Administrator")]
        public ActionResult Edit(int id = 0)
        {
            SanPham sanpham = db.SanPhams.Find(id);
            if (sanpham == null)
            {
                return HttpNotFound();
            }
            return View(sanpham);
        }

        //
        // POST: /SanPham/Edit/5
        [Authorize(Roles = "Administrator")]
        [HttpPost]
        public ActionResult Edit(SanPham sanpham, FormCollection form)
        {
            if (ModelState.IsValid)
            {
                int idSP = Convert.ToInt32(form["ID"]);
                var oldSP = db.SanPhams.Find(idSP);
                var oldMaSP = oldSP.MaSP;
                string[] listMSP;
                List<XuatKho> xks = db.XuatKhoes.Where(p => p.Ma_SP.Contains(oldMaSP + ";#")).ToList();
                if (xks != null && xks.Count > 0)
                {
                    foreach (XuatKho xk in xks)
                    {
                        listMSP = xk.Ma_SP.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                        int index = Array.IndexOf(listMSP, oldMaSP);
                        if (index >= 0)
                        {
                            xk.Ma_SP = xk.Ma_SP.Replace(oldMaSP, sanpham.MaSP);
                            db.Entry(xk).State = EntityState.Modified;
                            db.SaveChanges();
                        }
                    }
                }

                List<NhapKho> nks = db.NhapKhoes.Where(p => p.Ma_SP.Contains(oldMaSP + ";#")).ToList();
                if (nks != null && nks.Count > 0)
                {
                    foreach (NhapKho nk in nks)
                    {
                        listMSP = nk.Ma_SP.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                        int index = Array.IndexOf(listMSP, oldMaSP);
                        if (index >= 0)
                        {
                            nk.Ma_SP = nk.Ma_SP.Replace(oldMaSP, sanpham.MaSP);
                            db.Entry(nk).State = EntityState.Modified;
                            db.SaveChanges();
                        }
                    }
                }
                this.db.Entry<SanPham>(oldSP).CurrentValues.SetValues(sanpham);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(sanpham);
        }

        //
        // GET: /SanPham/Delete/5
        [Authorize(Roles = "Administrator")]
        public JsonResult Delete(int id)
        {
            SanPham sanpham = db.SanPhams.Find(id);
            sanpham.Disable = "disable";
            db.Entry(sanpham).State = EntityState.Modified;
            db.SaveChanges();
            return Json(new { msg = "success" });
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}